"use client"

import { useEffect, useRef, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Heart, SkipBack, Play, Pause, SkipForward, Volume2, List } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { usePlayer } from "@/contexts/player-context"
import { toast } from "@/components/ui/use-toast"
import { cn } from "@/lib/utils"
import { usePathname } from "next/navigation"

export function PlayerBar() {
  const {
    state: { currentSong, isPlaying, volume, progress },
    togglePlay,
    setVolume,
    setProgress,
    nextSong,
    previousSong,
  } = usePlayer()

  const [isFavorited, setIsFavorited] = useState(false)
  const audioRef = useRef<HTMLAudioElement>(null)
  const pathname = usePathname()
  const isPlaylistOpen = pathname === "/playlist-view"
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)



  // Function to toggle favorite status
  const toggleFavorite = async () => {
    if (!currentSong) return
    try {
      const method = isFavorited ? "DELETE" : "POST"
      const response = await fetch("/api/user/favorites", {
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ songId: currentSong.id }),
      })

      if (response.ok) {
        setIsFavorited(!isFavorited)
        toast({
          title: isFavorited ? "已移除收藏" : "已添加到我喜欢的音乐",
          description: `${currentSong.title} - ${currentSong.artists}`,
        })
      }
    } catch (error) {
      console.error("Error toggling favorite:", error)
      toast({
        title: "操作失败",
        description: "请稍后重试"
      })
    }
  }

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume
    }
  }, [volume])

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume
      if (isPlaying) {
        audioRef.current.play().catch((error) => {
          console.error("Playback failed:", error)
          toast({
            title: "播放失败",
            description: "无法播放该音频，请稍后重试"
          })
        })
      } else {
        audioRef.current.pause()
      }
    }
  }, [isPlaying, volume])

  useEffect(() => {
    if (currentSong) {
      setCurrentTime(0)
      setDuration(0)
    }
  }, [currentSong])

  const formatTime = (time: number) => {
    if (!isFinite(time)) return "0:00"
    const minutes = Math.floor(time / 60)
    const seconds = Math.floor(time % 60)
    return `${minutes}:${seconds.toString().padStart(2, "0")}`
  }

  const handleProgressChange = (newProgress: number[]) => {
    const audio = audioRef.current
    if (audio && isFinite(audio.duration) && isFinite(newProgress[0])) {
      const newTime = (newProgress[0] / 100) * audio.duration
      if (isFinite(newTime)) {
        audio.currentTime = newTime
        setProgress(newTime / audio.duration)
      }
    }
  }

  if (!currentSong) {
    return null
  }

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-background/80 backdrop-blur-md border-t z-50">
      <div className="container mx-auto px-4">
        {/* Progress bar */}
        <div className="relative h-1 -mt-[1px] group">
          <div className="absolute inset-0 bg-muted overflow-hidden">
            <div className="h-full bg-primary transition-all" style={{ width: `${progress * 100}%` }} />
          </div>
          <Slider
            value={[progress * 100]}
            max={100}
            step={0.1}
            className="absolute inset-0 opacity-0 group-hover:opacity-100"
            onValueChange={handleProgressChange}
          />
        </div>

        <div className="h-20 flex items-center justify-between gap-4">
          {/* Song info */}
          <Link href="/now-playing" className="flex items-center gap-4 min-w-0 w-[30%]">
            <div className="relative aspect-square h-14 flex-shrink-0">
              <Image
                src={currentSong.cover || "/placeholder.svg"}
                alt={currentSong.title}
                fill
                className="object-cover rounded"
              />
            </div>
            <div className="min-w-0">
              <div className="font-medium truncate">{currentSong.title}</div>
              <div className="text-sm text-muted-foreground truncate">{currentSong.artists}</div>
            </div>
          </Link>

          {/* Playback controls */}
          <div className="flex flex-col items-center gap-1 flex-1">
            <div className="flex items-center gap-4">
              <Button
                variant="ghost"
                size="icon"
                className="h-10 w-10 text-muted-foreground hover:text-foreground"
                onClick={previousSong}
              >
                <SkipBack className="h-5 w-5" />
              </Button>
              <Button size="icon" className="h-10 w-10" onClick={togglePlay}>
                {isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-10 w-10 text-muted-foreground hover:text-foreground"
                onClick={nextSong}
              >
                <SkipForward className="h-5 w-5" />
              </Button>
            </div>
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <span>{formatTime(currentTime)}</span>
              <span>/</span>
              <span>{formatTime(duration)}</span>
            </div>
          </div>

          {/* Volume and actions */}
          <div className="flex items-center gap-4 w-[30%] justify-end">
            <Button
              variant="ghost"
              size="icon"
              className={cn(
                "h-10 w-10 text-muted-foreground hover:text-foreground",
                isFavorited && "text-red-500 hover:text-red-600",
              )}
              onClick={toggleFavorite}
            >
              <Heart className={cn("h-5 w-5", isFavorited && "fill-current")} />
            </Button>
            <div className="flex items-center gap-2 group/volume">
              <Volume2 className="h-4 w-4 text-muted-foreground" />
              <div className="w-[100px] hidden group-hover/volume:block">
                <Slider value={[volume * 100]} max={100} step={1} onValueChange={([value]) => setVolume(value / 100)} />
              </div>
            </div>
            {isPlaylistOpen ? (
              <Button
                variant="ghost"
                size="icon"
                className="h-10 w-10 text-muted-foreground hover:text-foreground"
                onClick={() => window.history.back()}
              >
                <List className="h-5 w-5" />
              </Button>
            ) : (
              <Link href="/playlist-view">
                <Button variant="ghost" size="icon" className="h-10 w-10 text-muted-foreground hover:text-foreground">
                  <List className="h-5 w-5" />
                </Button>
              </Link>
            )}
          </div>
        </div>
      </div>

      <audio
        ref={audioRef}
        src={currentSong?.url}
        onError={() => {
          toast({
            title: "播放错误",
            description: "音频文件加载失败"
          })
        }}
        onTimeUpdate={() => {
          const audio = audioRef.current
          if (audio && isFinite(audio.currentTime) && isFinite(audio.duration)) {
            setCurrentTime(audio.currentTime)
            setProgress(audio.currentTime / audio.duration)
          }
        }}
        onLoadedMetadata={() => {
          const audio = audioRef.current
          if (audio && isFinite(audio.duration)) {
            setDuration(audio.duration)
          }
        }}
        onEnded={nextSong}
      />
    </div>
  )
}

